package com.whq.mvc.base.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisPool {

    private static JedisPool pool;

    // 最大连接数
    private static Integer maxTotal = Integer.parseInt(
            PropertiesUtils.getProperty("redis.max.total", "20"));
    // 最大空闲数
    private static Integer maxIdle = Integer.parseInt(
            PropertiesUtils.getProperty("redis.max.idle", "10"));
    // 最小空闲数
    private static Integer minIdle = Integer.parseInt(
            PropertiesUtils.getProperty("redis.min.idle", "2"));
    // 从jedis连接池获取连接时，校验并返回可用的连接
    private static Boolean testOnBorrow = Boolean.parseBoolean(
            PropertiesUtils.getProperty("redis.test.borrow", "true"));
    // 把连接放回jedis连接池时，校验并返回可用的连接
    private static Boolean testOnReturn = Boolean.parseBoolean(
            PropertiesUtils.getProperty("redis.test.return", "true"));

    private static String redisIp = PropertiesUtils.getProperty("redis.ip", "127.0.0.1");
    private static Integer redisPort = Integer.parseInt(
            PropertiesUtils.getProperty("redis.port", "6379"));
    private static String redisPass = PropertiesUtils.getProperty("redis.password", "123456");

    static {
        initPool();
    }

    private static void initPool(){
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);
        config.setBlockWhenExhausted(true);
        pool = new JedisPool(config, redisIp, redisPort, 3 * 1000, redisPass);
    }

    public static Jedis getJedis(){
        return pool.getResource();
    }

    public static void returnResource(Jedis jedis){
        jedis.close();
    }
}
